<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          @click="toQuery"
          size="mini">
          查询结果
        </el-button>
        <el-button
          @click="resetSearch"
          style="float: right;margin-right: 15px"
          size="mini">
          重置
        </el-button>
        <el-button
          v-permission="['admin','media:add']"
          @click="add"
          style="float: right;margin-right: 10px"
          class="btn-add"
          type="success"
          size="mini">
          添加
        </el-button>
      </div>
      <div style="margin-top: 20px">
        <el-form :inline="true" size="small" label-width="100px">
          <el-form-item label="id：">
            <el-input style="width: 180px" v-model="query.id" placeholder="请输入id" clearable
                      @change="toQuery"></el-input>
          </el-form-item>
          <el-form-item label="名字：">
            <el-input style="width: 180px" v-model="query.name" placeholder="名字模糊匹配" clearable
                      @change="toQuery"></el-input>
          </el-form-item>
          <el-form-item label="类型：">
            <el-select style="width: 100px" v-model="query.type" clearable @change="toQuery" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间：">
            <el-date-picker
              @change="toQuery"
              v-model="query.time"
              type="datetimerange"
              range-separator=":"
              class="el-range-editor--small filter-item"
              style="float: right;height: 30.5px;width: 350px"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-table v-loading="loading" border style="margin-top: 15px" :data="data" row-key="id" size="small">
      <el-table-column fixed="left" width="180" align="center" label="id" prop="id">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="点我复制" placement="top-start">
            <span style="cursor: pointer" v-copy:callback="handleCopied" v-copy="scope.row.id">{{scope.row.id}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column fixed="left" width="180" align="center" label="名字" prop="name"/>
      <el-table-column fixed="left" width="180" align="center" label="缩略图" prop="url">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="50" :src="squareUrl(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column fixed="left" width="180" align="center" label="类型" prop="type">
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.type===1">
            图片
          </el-tag>
          <el-tag type="success" v-if="scope.row.type===2">
            视频
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="left" align="center" label="备注" prop="remark"/>
      <el-table-column align="center" width="180" prop="createTime" label="创建日期">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px"
                       align="center" fixed="right">
        <template slot-scope="scope">
          <el-button v-permission="['admin','media:update']" size="mini" type="primary"
                     :icon="'el-icon-s-tools'"
                     v-if="scope.row.type===1"
                     @click="hotZoneConfig(scope.row)">
          </el-button>
          <el-button v-permission="['admin','media:update']" size="mini" type="primary"
                     :icon="'el-icon-edit'"
                     @click="edit(scope.row)">
          </el-button>
          <el-popover
            :ref="scope.row.id"
            placement="top"
            width="200">
            <p>确定删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定
              </el-button>
            </div>
            <el-button v-permission="['admin','media:del']" slot="reference"
                       type="danger" icon="el-icon-delete" size="mini">
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="page + 1"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"/>

    <el-dialog top="20" :visible.sync="dialog" :close-on-click-modal="false" :before-close="cancel"
               :title="isAdd ? '新增媒体资源' : '编辑媒体资源'" append-to-body width="50%">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="20%">
        <el-form-item label="名字：" prop="name">
          <el-input v-model="form.name" style="width: 80%;" placeholder="名字"/>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.remark" style="width: 80%;" type="textarea" placeholder="备注"/>
        </el-form-item>
        <el-form-item label="类型：" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">图片</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频封面：" v-if="form.type===2" prop="coverUrl">
          <el-upload
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :headers="headers"
            :action="fileUploadApi"
            class="avatar-uploader">
            <img v-if="form.coverUrl" :src="form.coverUrl" title="点击上传封面" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传图片或视频：" prop="url">
          <el-upload
            style="width: 70%;"
            list-type="picture"
            class="upload-demo"
            :limit="1"
            :on-remove="handleUrRemove"
            :on-success="handleUrSuccess"
            :on-error="handleError"
            :headers="headers"
            :file-list="form.url"
            :action="fileUploadApi"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
    <hot-zone ref="hotZone"/>
  </div>
</template>

<script>
  import initData from '@/mixins/initData'
  import {parseTime} from '@/utils/index'
  import {mapGetters} from 'vuex'
  import {getToken} from '@/utils/auth'
  import {add, update, del} from '@/api/business/mediaApi'
  import hotZone from "./hotZone";

  export default {
    mixins: [initData],
    components: {hotZone},
    computed: {
      ...mapGetters([
        'fileUploadApi',
      ])
    },
    name: "index",
    data() {
      return {
        typeOptions: [
          {
            value: 1,
            label: '图片'
          }, {
            value: 2,
            label: '视频'
          }
        ],
        headers: {
          'Authorization': 'Bearer ' + getToken()
        },
        isAdd: true,
        delLoading: false,
        loading: false, dialog: false,
        form: {
          name: '',
          type: 1,
          coverUrl: '',
          url: [],
          createTime: '',
          hotZone: [],
          remark: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入名字', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择类型', trigger: 'blur'}
          ],
          coverUrl: [
            {required: true, message: '请上传视频封面', trigger: 'change'}
          ],
          url: [
            {required: true, message: '请上传资源', trigger: 'change'}
          ],
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      squareUrl(row) {
        if (row.type === 1) {
          return row.url[0].url
        } else {
          return row.coverUrl
        }
      },
      hotZoneConfig(row) {
        this.$refs.hotZone.setup(row)
      },
      handleUrRemove(response, file, fileList) {
        this.$notify({
          title: '上传成功',
          type: 'success',
          duration: 2500
        })
        this.form.url = []
      },
      handleUrSuccess(response, file, fileList) {
        this.form.url = []
        this.$notify({
          title: '上传成功',
          type: 'success',
          duration: 2500
        })
        this.form.url.push({
          name: file.name,
          uid: file.uid,
          url: response.data
        })
      },
      handleSuccess(response, file, fileList) {
        this.$notify({
          title: '上传成功',
          type: 'success',
          duration: 2500
        })
        this.form.coverUrl = response.data
      },
      handleError(e, file, fileList) {
        const msg = JSON.parse(e.message)
        this.$notify({
          title: msg.message,
          type: 'error',
          duration: 2500
        })
      },
      cancel() {
        this.resetForm()
      },
      resetForm() {
        this.dialog = false
        this.$refs['form'].resetFields()
        this.form = {
          name: '',
          type: 1,
          coverUrl: '',
          url: [],
          createTime: '',
          hotZone: [],
          remark: ''
        }
      },
      subDelete(id) {
        this.delLoading = true
        del(id).then(res => {
          this.delLoading = false
          this.$refs[id].doClose()
          this.init()
          this.$notify({
            title: '删除成功',
            type: 'success',
            duration: 2500
          })
        }).catch(err => {
          this.delLoading = false
          this.$refs[id].doClose()
        })
      },
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.isAdd) {
              this.doAdd()
            } else this.doEdit()
          } else {
            return false
          }
        })
      },
      doAdd() {
        add(this.form).then(res => {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.init()
        }).catch(err => {
          this.loading = false
        })
      },
      doEdit() {
        update(this.form).then(res => {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.init()
        }).catch(err => {
          this.loading = false
        })
      },
      edit(data) {
        this.isAdd = false
        this.form = {
          id: data.id,
          name: data.name,
          type: data.type,
          coverUrl: data.coverUrl,
          url: data.url,
          hotZone: data.hotZone,
          remark: data.remark
        };
        this.dialog = true
      },
      add() {
        this.dialog = true;
        this.isAdd = true;
      },
      parseTime,
      beforeInit() {
        this.url = 'api/media/list'
        this.params = {page: this.page, size: this.size}
        const query = this.query
        if (query.name) {
          this.params['name'] = query.name
        }
        if (query.type) {
          this.params['type'] = query.type
        }
        if (query.id) {
          this.params['id'] = query.id
        }
        if (query.time && query.time.length > 0) {
          this.params['startTime'] = query.time[0]
          this.params['endTime'] = query.time[1]
        }
        return true
      },
      resetSearch() {
        this.query = {}
        this.init()
      },
    }
  }
</script>

<style scoped>
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
